<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分组数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="groupName"
              placeholder="请输入分组名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="groupOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="groupTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--文件数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="文件名称" prop="fileName">
            <el-input
              v-model="queryParams.fileName"
              placeholder="请输入文件名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable style="width: 180px">
              <el-option
                v-for="dict in file_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="上传时间" style="width: 308px;">
            <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['file:file:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['file:file:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['file:file:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['file:file:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="文件编号" align="center" prop="fileId" />
          <el-table-column label="文件名称" align="center" prop="fileName" v-if="columns[0].visible" />
          <el-table-column label="文件类型" align="center" prop="fileType" v-if="columns[1].visible">
            <template #default="scope">
              <dict-tag :options="file_type" :value="scope.row.fileType"/>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" align="center" prop="fileSize" v-if="columns[2].visible" />

<!--          <el-table-column label="文件位置" align="center" prop="fileUrl" v-if="columns[3].visible" />-->
          <el-table-column label="文件位置" align="center" prop="fileUrl" width="100" v-if="columns[3].visible">
            <template #default="scope">
              <image-preview :src="scope.row.fileUrl" :width="50" :height="50"/>
            </template>
          </el-table-column>

          <el-table-column label="文件分组" align="center" prop="groupName" v-if="columns[4].visible" />
          <el-table-column label="备注信息" align="center" prop="remark" v-if="columns[6].visible" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['file:file:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['file:file:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改文件管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="fileRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="文件分组" prop="groupId">
          <el-tree-select v-model="form.groupId" :data="groupOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择文件分组" check-strictly />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择文件类型">
            <el-option
              v-for="dict in file_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件列表" prop="fileUrl">
          <image-upload v-model="form.fileUrl"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="File">
import { listFile, getFile, delFile, addFile, updateFile, groupTreeSelect } from "@/api/file/file";

const { proxy } = getCurrentInstance();
const { file_type, sys_normal_disable } = proxy.useDict('file_type', 'sys_normal_disable');

const fileList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const groupName = ref("");
const groupOptions = ref(undefined);

// 列显隐信息
const columns = ref([
  { key: 0, label: `文件名称`, visible: true },
  { key: 1, label: `文件类型`, visible: true },
  { key: 2, label: `文件大小`, visible: true },
  { key: 3, label: `文件位置`, visible: true },
  { key: 4, label: `文件分组`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `备注信息`, visible: true },
]);

const data = reactive({
  // 表单参数
  form: {},
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileName: null,
    fileType: null,
    fileSize: null,
    fileUrl: null,
    groupId: null,
    status: null,
    createTime: null,
  },
  rules: {
    fileName: [
      { required: true, message: "文件名称不能为空", trigger: "blur" }
    ],
    fileType: [
      { required: true, message: "文件类型不能为空", trigger: "change" }
    ],
    fileSize: [
      { required: true, message: "文件大小不能为空", trigger: "blur" }
    ],
    fileUrl: [
      { required: true, message: "文件位置不能为空", trigger: "blur" }
    ],
    groupId: [
      { required: true, message: "文件分组不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选树 */
watch(groupName, val => {
  proxy.$refs["groupTreeRef"].filter(val);
});

/** 查询下拉树结构 */
function getGroupTree() {
  groupTreeSelect().then(response => {
    groupOptions.value = response.data;
  });
};

/** 查询文件管理列表 */
function getList() {
  loading.value = true;
  const dateRangeValue = Array.isArray(dateRange.value) ? dateRange.value : [];
  queryParams.value.beginTime = dateRangeValue[0];
  queryParams.value.endTime = dateRangeValue[1];
  listFile(queryParams.value).then(response => {
    fileList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.groupId = data.id;
  handleQuery();
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    fileId: null,
    fileName: null,
    fileType: null,
    fileSize: null,
    fileUrl: null,
    groupId: null,
    status: null,
    delFlag: null,
    version: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("fileRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.groupId = undefined;
  proxy.$refs.groupTreeRef.setCurrentKey(null);
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.fileId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文件管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _fileId = row.fileId || ids.value
  getFile(_fileId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改文件管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["fileRef"].validate(valid => {
    if (valid) {
      if (form.value.fileId != null) {
        updateFile(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addFile(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _fileIds = row.fileId || ids.value;
  proxy.$modal.confirm('是否确认删除文件管理编号为"' + _fileIds + '"的数据项？').then(function() {
    return delFile(_fileIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('file/file/export', {
    ...queryParams.value
  }, `file_${new Date().getTime()}.xlsx`)
}

getGroupTree();
getList();
</script>
